package com.wangjiacai.utils.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;

public class BytesUtil {

    public static int getInt(byte[] bytes,int position){
        ByteBuffer buffer=ByteBuffer.wrap(bytes,position,4);
        return buffer.getInt();
    }

    public static long getLong(byte[] bytes,int position){
        ByteBuffer buffer=ByteBuffer.wrap(bytes,position,8);
        return buffer.getLong();
    }

    public static byte[] intToBytes(int num,int size){
        byte[] bytes=new byte[size];
        for(int i=0;i<size;i++){
            bytes[i]=(byte)(num>>(size-i-1)*8&0xff);
        }
        return bytes;
    }

    public static byte[] getLittleBytes(int num,int size){
        byte[] bytes=new byte[size];
        for(int i=0;i<size;i++){
            bytes[i]=(byte)(num>>i*8&0xff);
        }
        return bytes;
    }

    public static int getIntLittleBytes(byte[] bytes){
        ByteBuffer buffer=ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getInt();
    }

    public static byte[] getAllBytes(List<byte[]> list){
        int size = 0;
        for (byte[] bytes : list) {
            size += bytes.length;
        }
        byte[] bytes = new byte[size];
        int position = 0;
        for (byte[] bs : list) {
            for (byte b : bs) {
                bytes[position++] = b;
            }
        }
        return bytes;
    }

}
